<?php
// 纯PHP+PDO版本的城市坐标更新脚本

// 设置脚本执行时间限制
set_time_limit(0);
ini_set('memory_limit', '512M');

echo "开始更新城市坐标信息...\n";
echo "执行时间: " . date('Y-m-d H:i:s') . "\n";
echo "========================================\n";

// 数据库配置
$dbConfig = [
    'host' => '127.0.0.1',
    'dbname' => 'dev002_gxyusheng',
    'username' => 'root',
    'password' => '159456',
    'charset' => 'utf8mb4',
    'prefix' => 'fa_'
];

// 百度地图API配置
$baiduConfig = [
    'ak_fw' => 'aBIfRNb8MimBirL5RrjJn1WKDGs0jVQE',
    'ak' => 'HX3XrjGHigjidfWYSf6bozZbiABeWfUX'
];

// 创建PDO连接
function createPDOConnection($config) {
    try {
        $dsn = "mysql:host={$config['host']};dbname={$config['dbname']};charset={$config['charset']}";
        $pdo = new PDO($dsn, $config['username'], $config['password'], [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES {$config['charset']}"
        ]);
        return $pdo;
    } catch (PDOException $e) {
        throw new Exception("数据库连接失败: " . $e->getMessage());
    }
}

// 简化的地理编码函数
function getLocationSimple($cityName, $baiduConfig) {
    $ak = $baiduConfig['ak_fw'];
    
    if (empty($ak)) {
        throw new Exception("百度地图API密钥未配置");
    }
    
    echo "使用API密钥: " . substr($ak, 0, 8) . "...\n";
    
    // 构建请求参数
    $params = [
        "address" => $cityName,
        "city" => $cityName,
        "output" => 'json',
        "ak" => $ak,
    ];
    
    $queryStr = http_build_query($params);
    $apiUrl = "https://api.map.baidu.com/geocoding/v3/?" . $queryStr;
    
    echo "请求URL: " . $apiUrl . "\n";
    
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $apiUrl,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_TIMEOUT => 10,
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
        ],
    ]);
    
    $res = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlError = curl_error($ch);
    curl_close($ch);
    
    // 检查CURL错误
    if ($curlError) {
        throw new Exception("CURL错误: " . $curlError);
    }
    
    // 检查HTTP状态码
    if ($httpCode != 200) {
        throw new Exception("HTTP错误: " . $httpCode);
    }
    
    echo "API响应: " . $res . "\n";
    
    $data = json_decode($res, true);
    
    // 详细的错误信息输出
    if (!$data) {
        throw new Exception("API返回数据解析失败: " . $res);
    }
    
    if (isset($data['status']) && $data['status'] != 0) {
        $errorMsg = $data['message'] ?? '未知错误';
        throw new Exception("百度地图API错误: " . $errorMsg . " (状态码: " . $data['status'] . ")");
    }
    
    // 检查返回数据结构
    if (!isset($data['result']) || !isset($data['result']['location'])) {
        throw new Exception("百度地图API返回数据格式错误: " . $res);
    }
    
    $location = $data['result']['location'];
    return [
        'latitude' => $location['lat'],
        'longitude' => $location['lng'],
    ];
}

try {
    // 创建数据库连接
    $pdo = createPDOConnection($dbConfig);
    echo "数据库连接成功\n";
    
    // 获取需要更新的城市列表
    $sql = "SELECT id, name FROM {$dbConfig['prefix']}cityarea 
            WHERE (latitude IS NULL OR latitude = '' OR longitude IS NULL OR longitude = '') 
            LIMIT 50";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute();
    $cities = $stmt->fetchAll();
    
    if (empty($cities)) {
        echo "没有需要更新坐标的城市记录\n";
        exit(0);
    }
    
    echo "找到 " . count($cities) . " 个需要更新的城市\n";
    echo "========================================\n";
    
    $successCount = 0;
    $errorCount = 0;
    
    foreach ($cities as $city) {
        echo "\n处理城市: {$city['name']} (ID: {$city['id']})\n";
        
        try {
            // 获取坐标
            $location = getLocationSimple($city['name'], $baiduConfig);
            
            // 更新数据库
            $updateSql = "UPDATE {$dbConfig['prefix']}cityarea 
                         SET latitude = :latitude, longitude = :longitude 
                         WHERE id = :id";
            
            $updateStmt = $pdo->prepare($updateSql);
            $updateResult = $updateStmt->execute([
                ':latitude' => $location['latitude'],
                ':longitude' => $location['longitude'],
                ':id' => $city['id']
            ]);
            
            if ($updateResult && $updateStmt->rowCount() > 0) {
                echo "✓ 成功更新: {$city['name']} -> 纬度: {$location['latitude']}, 经度: {$location['longitude']}\n";
                $successCount++;
            } else {
                echo "✗ 数据库更新失败: {$city['name']}\n";
                $errorCount++;
            }
            
        } catch (Exception $e) {
            echo "✗ 处理失败: {$city['name']} - " . $e->getMessage() . "\n";
            $errorCount++;
        }
        
        // 添加延时，避免API频率限制
        sleep(1);
    }
    
    echo "\n========================================\n";
    echo "处理完成!\n";
    echo "成功: {$successCount} 个\n";
    echo "失败: {$errorCount} 个\n";
    echo "结束时间: " . date('Y-m-d H:i:s') . "\n";
    
} catch (Exception $e) {
    echo "脚本执行错误: " . $e->getMessage() . "\n";
    exit(1);
}